package com.comum.javahomework420242025.controller;

import com.comum.javahomework420242025.mapper.DepartmentProductionMapper;
import com.comum.javahomework420242025.mapper.UserMapper;
import com.comum.javahomework420242025.pojo.*;
import com.comum.javahomework420242025.repository.ContractRepository;
import com.comum.javahomework420242025.repository.DepartmentProductionRepository;
import com.comum.javahomework420242025.repository.QuoteAndPSRepository;
import com.comum.javahomework420242025.repository.QuoteRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@RestController
public class QuoteController {
    @Autowired
    private QuoteRepository quoteRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuoteAndPSRepository quoteAndPSRepository;
    @Autowired
    private DepartmentProductionRepository departmentProductionRepository;
    @Autowired
    private DepartmentProductionMapper departmentProductionMapper;
    @Autowired
    private ContractRepository contractRepository;
    @PostMapping("/addQuote")
    public Result<Long> addQuote(@RequestBody Quote quote){
        quote.setId(null);
        LocalDate today = LocalDate.now();
        // 创建一个DateTimeFormatter对象，并设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将当前日期格式化为字符串
        String formattedDate = today.format(formatter);
        quote.setQuotedate(formattedDate);
        Quote ans = quoteRepository.save(quote);
        return Result.success(ans.getId());
    }
    @PostMapping("/addQuoteAndProductionPS")
    public Result addQuoteAndProductionPS(
            String quoteid,
            @RequestBody List<DepartmentProductionForResult> ccf){
        for(DepartmentProductionForResult a:ccf){
            if(!a.getSelectnumber().equals((long)0)){//客户选择
                QuoteAndProductionPS res = new QuoteAndProductionPS();
                res.setId(null);res.setSelectnumber(a.getSelectnumber());
                res.setDepartmentproductionid(a.getId());
                res.setQuoteid(Long.valueOf(quoteid));
                res.setAllprice(a.getAllprice());
                Optional<DepartmentProduction> dpdata = departmentProductionRepository.findById(a.getId());
                DepartmentProduction dp = dpdata.get();
                dp.setNumber(dp.getNumber() - a.getSelectnumber());
                departmentProductionRepository.save(dp);
                quoteAndPSRepository.save(res);
            }
        }
        return Result.success();
    }
    @PostMapping("/updateQuote")
    public Result updateQuote(@RequestBody Quote quote){
        LocalDate today = LocalDate.now();
        // 创建一个DateTimeFormatter对象，并设置日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将当前日期格式化为字符串
        String formattedDate = today.format(formatter);
        quote.setQuotedate(formattedDate);
        quoteRepository.save(quote);
        return Result.success();
    }
    @PutMapping("/updateQuoteAndProductionPS")
    public Result updateQuoteAndProductionPS(
            String quoteid,
            @RequestBody List<DepartmentProductionForResult> ccf){
        for(DepartmentProductionForResult a:ccf){ //给我干秃头了，tmd
            if(!a.getSelectnumber().equals((long)0)&&a.getQuoteandproductionpsid()!=null){
                //选择不变成0，数据库有记录
                Optional<QuoteAndProductionPS> qps =  quoteAndPSRepository.findById(a.getQuoteandproductionpsid());
                Long cha = qps.get().getSelectnumber() - a.getSelectnumber();

                Optional<DepartmentProduction> dpdata = departmentProductionRepository.findById(a.getId());
                DepartmentProduction dp = dpdata.get();
                dp.setNumber(dp.getNumber() + cha);

                departmentProductionRepository.save(dp);
                QuoteAndProductionPS res = new QuoteAndProductionPS();
                res.setId(a.getQuoteandproductionpsid());
                res.setSelectnumber(a.getSelectnumber());
                res.setDepartmentproductionid(a.getId());
                res.setQuoteid(Long.valueOf(quoteid));
                res.setAllprice(a.getAllprice());
                quoteAndPSRepository.save(res);
            } else if (a.getSelectnumber().equals((long)0)&&a.getQuoteandproductionpsid()!=null) {
                //选择变成0，数据库有记录
                Optional<QuoteAndProductionPS> qps =  quoteAndPSRepository.findById(a.getQuoteandproductionpsid());
                Long cha = qps.get().getSelectnumber() - a.getSelectnumber();

                Optional<DepartmentProduction> dpdata = departmentProductionRepository.findById(a.getId());
                DepartmentProduction dp = dpdata.get();
                dp.setNumber(dp.getNumber() + cha);

                departmentProductionRepository.save(dp);
                quoteAndPSRepository.deleteById(a.getQuoteandproductionpsid());
            } else if (!a.getSelectnumber().equals((long)0)&&a.getQuoteandproductionpsid()==null) {
                //选择不变成0，数据库没有记录
                QuoteAndProductionPS res = new QuoteAndProductionPS();
                res.setId(null);res.setSelectnumber(a.getSelectnumber());
                res.setDepartmentproductionid(a.getId());
                res.setQuoteid(Long.valueOf(quoteid));
                res.setAllprice(a.getAllprice());
                Optional<DepartmentProduction> dpdata = departmentProductionRepository.findById(a.getId());
                DepartmentProduction dp = dpdata.get();
                dp.setNumber(dp.getNumber() - a.getSelectnumber());
                departmentProductionRepository.save(dp);
                quoteAndPSRepository.save(res);
            }
        }
        return Result.success();
    }
    @PostMapping("/getQuote")
    public Result<PageBean<Quote>> getQuote(
            @RequestBody AskList askList,HttpServletRequest req){
        int pageSize = askList.getPageSize();
        int pageNum = askList.getPageNum();
        String str = askList.getStr();
        HttpSession session = req.getSession();
        Long userid = (Long) session.getAttribute("userid");
        String department = userMapper.joinAreaGetDepartmentByuserid(userid);
        PageBean<Quote> pb = new PageBean<>();
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<Quote> page = quoteRepository.getQuote(str,department,pageable);
        pb.setTotal(page.getTotalElements());
        pb.setItems(page.getContent());
        return Result.success(pb);
    }
    @GetMapping("/loadquoteproductions")
    public Result<List<DepartmentProductionForResult>>loadquoteproductions(
            String quoteid, HttpServletRequest req
    ){
        HttpSession session = req.getSession();
        Long userid = (Long) session.getAttribute("userid");
        String department = userMapper.joinAreaGetDepartmentByuserid(userid);
        List<DepartmentProductionForResult> selectres = departmentProductionMapper.findselectproductions(quoteid);
        List<DepartmentProductionForResult> allres = departmentProductionMapper.selectByStrForQuote("",department);
        for (int i = 0; i < allres.size(); i++) {
            int f=0;
            for (DepartmentProductionForResult selectItem : selectres) {
                if(allres.get(i).getSelectnumber()==null&&allres.get(i).getAllprice()==null
                &&allres.get(i).getId().equals(selectItem.getDepartmentproductionid())){
                    allres.get(i).setSelectnumber(selectItem.getSelectnumber());
                    allres.get(i).setAllprice(selectItem.getAllprice());
                    allres.get(i).setQuoteandproductionpsid(selectItem.getId());
                    f=1;
                    break;
                }
            }
            if(f==0){
                allres.get(i).setSelectnumber((long)0);
                allres.get(i).setAllprice(0.0);
            }
            System.out.println(allres.get(i));
        }
        return Result.success(allres);
    }
    @DeleteMapping("/deletequote")
    public Result deletequote(String id){
        List<Contract> res = contractRepository.findByQuoteId(id);
        if(res.size()!=0) return Result.error("该报价关联其他信息，无法删除！");
        List<QuoteAndProductionPS> res2 = quoteAndPSRepository.findByQuoteId(id);
        if(res2.size()!=0) return Result.error("该报价已选择产品，请清空产品选择再删除！");
        quoteRepository.deleteById(Long.valueOf(id));
        return Result.success();
    }
}
